<?php

namespace App\Http\Middleware;
use App\Http\Controllers\Auth;
use App\Http\Controllers\AuthController;
use App\Models\User;
use App\Utils\CodeUtil;
use Closure;
class Login {
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next) {
        $user = session('admin_user');
        if (!empty($user)) {
            //User::where('id', session('uid'))->update(['last_login' => date('Y-m-d H:i:s', time())]);
            if($user["id"] != 1) {
                //无需走验证的页面
                $getActionName = request()->route()->getActionName();
                $getActionName_array = explode("@",$getActionName);
                $controller = str_replace("Controller","",array_last(explode("\\",$getActionName_array[0])));
                $function = array_last($getActionName_array);
                $result = $controller."_".$function;
                $notCheck = AuthController::$super;
                if (in_array($result,$notCheck)) 	return $next($request);
                //不是超级管理员角色，需要走Auth验证
                $auth = Auth::instance();
                if (!$auth->check($result, $user["id"],1,"check"))    return response()->json(['code'=> CodeUtil::API_ERROR,"msg"=> "对不起,无权限!"]);
            }
            // 权限
            return $next($request);
        } else {
            return redirect("/api/login");
        }
    }
}
